﻿#include "dialogpannel.h"
#include "ui_dialogpannel.h"
#include "tb_interface.h"
#include <QSpinBox>
#include <QLineEdit>
#include <QDoubleSpinBox>
#include <QScrollArea>
#include <QComboBox>
#include <QLabel>
#include <QGridLayout>
#include <QTimerEvent>
DialogPannel::DialogPannel(const TASKBUS::cmdlineParser * ps, QWidget *parent) :
	QDialog(parent),
	ui(new Ui::DialogPannel),
	m_log(new QStandardItemModel(this)),
	m_pCmd(ps),
	m_rthread(new reciv_thread(ps,this))
{
	ui->setupUi(this);
	ui->listView_log->setModel(m_log);
	connect(m_rthread,&reciv_thread::sig_quit,this,&DialogPannel::close);
	connect(m_rthread,&reciv_thread::new_message,this,&DialogPannel::deal_message,Qt::QueuedConnection);
	connect(m_rthread,&reciv_thread::new_data,this,&DialogPannel::deal_taskbus_input,Qt::QueuedConnection);
	connect(ui->console,&Console::getData,this,&DialogPannel::deal_console_input,Qt::QueuedConnection);
	Qt::WindowFlags flg = windowFlags();
	flg |= Qt::WindowMinMaxButtonsHint;
	setWindowFlags(flg);
	m_rthread->start();
	m_nTimer = startTimer(10);

	sub_output = m_pCmd->toInt("output",0);
	instance = m_pCmd->toInt("instance",0);
	m_maxPackSize = m_pCmd->toInt("max_pack",160);
	m_locale = m_pCmd->toInt("locale",0);
	if (m_maxPackSize<16)
		m_maxPackSize = 16;
	else if (m_maxPackSize>9000)
		m_maxPackSize = 9000;

	int la = m_pCmd->toInt("local_echo",1);
	ui->console->setLocalEchoEnabled(la!=0);
}

DialogPannel::~DialogPannel()
{
	m_rthread->terminate();
	m_rthread->wait();
	delete ui;
}

void DialogPannel::deal_message(QString message)
{
	m_log->appendRow(new QStandardItem(message));
	if (m_log->rowCount()>256)
		m_log->removeRows(0,m_log->rowCount()-256);
}

void DialogPannel::deal_console_input(QByteArray arr)
{
	m_arr_buf.append(arr);
}
void  DialogPannel::timerEvent(QTimerEvent *event)
{
	if (event->timerId()==m_nTimer)
	{
		killTimer(m_nTimer);
		if (m_arr_buf.size() && sub_output)
		{
			QString strAll = QString::fromUtf8(m_arr_buf);

			const int totalsz = strAll.size();
			for (int begin = 0; begin < totalsz;begin += m_maxPackSize)
			{
				int sendLen = m_maxPackSize;
				if (begin + sendLen > totalsz)
					sendLen = totalsz - begin;
				QString sub = strAll.mid(begin,sendLen);
				QByteArray bufdata = sub.toUtf8();
				TASKBUS::push_subject(sub_output,instance,bufdata.size(),(unsigned char *)bufdata.data());
			}
		}		
		m_arr_buf.clear();
		if (m_displayQueue.size())
			ui->console->putData(m_displayQueue,m_locale);
		m_displayQueue.clear();
		m_nTimer = startTimer(30);
	}
}

void DialogPannel::deal_taskbus_input(QByteArray arr)
{
	m_displayQueue.append(arr);
}
